package com.ultrapower.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import com.ultrapower.commons.utils.HttpUtilDemo;
import com.ultrapower.commons.utils.McAesencrypt;
import com.ultrapower.commons.utils.OperateOracle;
import com.ultrapower.commons.utils.StringUtils;
import com.ultrapower.model.SmsLog;
import com.ultrapower.service.IBlackListService;
import com.ultrapower.service.IResultService;
import com.ultrapower.service.ISmsLogService;
import com.ultrapower.service.impl.TestService;

/**
 * spring task 定时任务测试，适用于单系统
 * 注意：不适合用于集群
 * @author L.cm
 */
@Component
public class TestTask {
	protected Logger logger = LogManager.getLogger(getClass());
	
	@Autowired private CacheManager cacheManager;
	@Autowired private TestService testService;
	@Autowired
    private IResultService resultService;
	@Autowired
    private ISmsLogService smsLogService;
	@Autowired
    private IBlackListService blackListService;
//	@Autowired private RedisTemplate<String, Object> redisTemplate;
	
	//@Scheduled(cron = "0 5/20 * * * ?")
	public void cronTest() {
		// 测试手动存储cache
		Cache cache = cacheManager.getCache("hour");
		Integer xx = cache.get("x", new Callable<Integer>() {

			@Override
			public Integer call() throws Exception {
				return 111111;
			}
		});
		// 测试redis
//		redisTemplate.boundListOps("xxxx").leftPush("xxxx");
		
		// 测试注解
		testService.selectById(1L);
		testService.selectById(1L);
		testService.selectById(1L);
		
		logger.debug(xx);
		logger.debug(new Date());
	}
	
	/**
	 * timedTaskSendMsg 定时任务
	 * 注意：不适合用于集群
	 * @author polly
	 */
	//@Scheduled(cron = "0 0 10 1/1 * ?")
//	@Scheduled(cron = "0 5 0/1 * * ? ")
	//@Scheduled(cron = "0 0/5 * * * ? ")		
	public void timedTaskSendMsg(){
		try {
			//1.每天早上10点开始给疑是欺诈用户发送短信校验的定时程序,这里会判断如果已经发送过的用户就不会在发送短信
			//2.首先获取系统已经判断出来的疑似欺诈号码,并且是没有发过短信的
			List<String> list = resultService.getSendMsgData();
			System.out.println("首先获取系统已经判断出来的疑似欺诈号码的集合,并且是没有发过短信的");
			list = list.subList(0, 99);
			System.out.println("截取100个号码list.size():"+list.size());
			//3.这里将得到数据进行循环发送短信的操作
			//4.记住,这里的手机号是密文,必须先解密,然后调用接口
//			String token = HttpUtilDemo
//					.getToken(
//							"grant_type=client_credentials&client_id=20180927004540040&client_secret=35bfd69e1258585dc3eb7914e8ccd547",
//							"http://171.0.0.4:6011/OAuth/restOauth2Server/access_token");
			String token = HttpUtilDemo
					.getToken(
							"grant_type=client_credentials&client_id=20181120100194029&client_secret=c3ec82c4fd4f0a642d3393d57d885613",
							"http://10.25.104.39:7011/OAuth/restOauth2Server/access_token");
			System.out.println("获取token");
			//解密号码
			List<String> listPhone = McAesencrypt.MCAesdecrypt(list, "phoneNo");
			System.out.println("解密号码");
			Set<String> set = new HashSet<String>();
			Set<String> setPhone = new HashSet<String>();
			Set<String> setBlack = new HashSet<String>();
			//4.然后获取一线应用平台或者用户上传的疑似欺诈号码,并且是没有发过短信的(记住,这里是明文,不需要解密)
			List<String> list_black = blackListService.getSendMsgData();
			System.out.println("然后获取一线应用平台或者用户上传的疑似欺诈号码,并且是没有发过短信的(记住,这里是明文,不需要解密)");
			set.addAll(listPhone);
			set.addAll(list_black);
			setPhone.addAll(listPhone);
			setBlack.addAll(list_black);
//			for (int i = 0; i < list_black.size(); i++) {
			//这里获取历史已经发送过短信的号码进行判断,发送过的将不在发送短信
			List<String> isSendList = smsLogService.selectIsSendList();
			System.out.println("这里获取历史已经发送过短信的号码进行判断,发送过的将不在发送短信");
//			for (String phone:set) {
			System.out.println("set集合长度："+set.size());
			if(set.size()>0){
			String phone = "15872356966";
			System.out.println(!isSendList.contains(phone));
				//已经发送过的不进行短信发送了
				if(!isSendList.contains(phone)){
					System.out.println("开始发送短信："+phone);
//					String url = "http://171.0.0.4:7666/OpenEbus/httpService/UserService?access_token="
//							+ token + "&method=sendSMSInfo&format=json";
//					String url = "http://10.25.104.39:7001/OpenEbus/httpService/UserService?access_token="
//							+ token + "&method=sendSMSInfo&format=json";
					String url = "http://10.25.111.46:7001/OpenEbus/httpService/UserService?access_token="
							+ token + "&method=sendSMSInfo&format=json";
					System.out.println("调用短信接口："+url);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("telnum", phone);
					map.put("smparam", "1 中国移动温馨提示您，您的号码近期存在异常通话行为。为确保您的用卡安全，请于4小时内回复“SFYZ+身份证号码后六位”进行身份验证。超时未回复或回复错误系统将进行停机。详询10086");
					String msgStr = new JSONObject(map).toString();
					String result = HttpUtilDemo.sendMsg(msgStr, url);
					System.out.println("调用短信接口返回结果result："+result);
					String res_code = new JSONObject(result).getString("res_code");
					System.out.println("调用短信接口返回结果res_code："+res_code);
					//5.这里记录日志,将发送过的号码都记录下来
					if("0".equals(res_code)){
						SmsLog smsLog = new SmsLog();
						smsLog.setTelnum(phone);
						smsLog.setIssendmsg(1);
						smsLog.setCreateTime(new Date());
						smsLogService.insert(smsLog);
					}else{
						System.out.println("短信接口调用失败**************");
					}
				}
			}
//			}
			//6.这里将一线平台和系统分析的数据修改数据库中的状态(记住,这里又需要加密,因为数据库中是密文)
			List<String> tempPhoneList = new ArrayList<String>();
			tempPhoneList.addAll(setPhone);
			if(tempPhoneList.size()>10){
				tempPhoneList.subList(0, 9);
			}
			//List<String> aesPhone = McAesencrypt.MCAesencrypt(tempPhoneList, "phoneNo");
			System.out.println("6.这里将一线平台和系统分析的数据修改数据库中的状态(记住,这里又需要加密,因为数据库中是密文)");
			//for (int i = 0; i < aesPhone.size(); i++) {
			//	String phone = aesPhone.get(i);
				//resultService.updateState(phone);
			//}
			for (String phoneBlack:setBlack) {
				//blackListService.updateState(phoneBlack);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * timedTaskMsgReply 定时任务
	 * 注意：不适合用于集群
	 * @author polly
	 */
	//@Scheduled(cron = "0 0 15 1/1 * ?")
	//@Scheduled(cron = "0 0/5 * * * ? ")
	public void timedTaskMsgReply(){
		try {
			//1.这里判断发送过用户的短信是否校验成功,如果成功则不做任何操作,如果失败则调用停机接口
			System.out.println("1.这里判断发送过用户的短信是否校验成功,如果成功则不做任何操作,如果失败则调用停机接口");
			List<SmsLog> isSendList = smsLogService.selectIsSendData();
			OperateOracle oo = new OperateOracle();
			//当天早上十点
			String tenDateStr = StringUtils.initDateByDay();
			//当前时间
			String nowDateStr = StringUtils.initDateByNow();
			System.out.println("已经发送过短信的集合长度："+isSendList.size());
			for (int i = 0; i < isSendList.size(); i++) {
				SmsLog smsLog = isSendList.get(i);
				String telnum = smsLog.getTelnum();
				//这里获取今天早上10到当前时间
				System.out.println("连接数据库接口做号码的回复内容相关查询");
				Set<String> resSet = oo.SelectData(telnum,tenDateStr,nowDateStr);
//				String retcode = si.getRetcode();
				String describe = "";
				int answer_state = 0;
				if(resSet.size()>0){
					//如果这里返回过0那么表示这个用户已经验证正确,不需要判断其他状态
					if(resSet.contains("0")){
						describe = "尊敬的客户，您好！身份证校验正确【中国移动】";
						answer_state = 0;
					}else{
						if(resSet.contains("SM_90001")){
							describe = "尊敬的客户，您好！对不起，身份证校验不正确【中国移动】";
							answer_state = 1;
						}else if(resSet.contains("SM_90002")){
							describe = "尊敬的客户，您好！验证超时【中国移动】";
							answer_state = 2;
						}else{
							describe = "其他";
							answer_state = -1;
						}
					}
				}
				System.out.println(describe);
				smsLog.setIsreplymsg(1);
				smsLog.setReplystate(describe);
				smsLog.setCreateTime(new Date());
				smsLogService.updateById(smsLog);
				Map<String, Object> condition = new HashMap<String, Object>();
				List<String> tempPhoneList = new ArrayList<String>();
				tempPhoneList.add(telnum);
				List<String> aesPhone = McAesencrypt.MCAesencrypt(tempPhoneList, "phoneNo");
				String encryptionNum = aesPhone.get(0);
				condition.put("telephone", encryptionNum);
				condition.put("replystate", describe);
				condition.put("phone_no", telnum);
				condition.put("answer_state", answer_state);
				resultService.updateReplyMsg(condition);
				blackListService.updateReplyMsg(condition);
			}
			//2.如果校验失败,则直接调用停机接口
			//3.这里调用已经回复过短信并且未停机的号码
			List<SmsLog> list = smsLogService.selectStopData();
//			String token = HttpUtilDemo
//					.getToken(
//							"grant_type=client_credentials&client_id=20180927004540040&client_secret=35bfd69e1258585dc3eb7914e8ccd547",
//							"http://171.0.0.4:6011/OAuth/restOauth2Server/access_token");
			String token = HttpUtilDemo
					.getToken(
							"grant_type=client_credentials&client_id=20181120100194029&client_secret=c3ec82c4fd4f0a642d3393d57d885613",
							"http://10.25.104.39:7011/OAuth/restOauth2Server/access_token");
//			String stopUrl = "http://171.0.0.4:7666/OpenEbus/httpService/UserService?access_token="
//					+ token + "&method=BLCSStopOpenSubs&format=json";
//			String stopUrl = "http://10.25.104.39:7001/OpenEbus/httpService/UserService?access_token="
//					+ token + "&method=BLCSStopOpenSubs&format=json";
			String stopUrl = "http://10.25.111.46:7001/OpenEbus/httpService/UserService?access_token="
					+ token + "&method=BLCSStopOpenSubs&format=json";
			System.out.println("调用停机接口");
			System.out.println(stopUrl);
//			for (int i = 0; i < list.size(); i++) {
				SmsLog smsLog = list.get(0);
				Map<String, Object> stopNetworkMap = new HashMap<String, Object>();
				//stopNetworkMap.put("servNumber", "15072196277");//15072494776//15072196277
//				stopNetworkMap.put("servNumber", smsLog.getTelnum());
				stopNetworkMap.put("servNumber", "15872356966");
				stopNetworkMap.put("recType", "StopSubs");
				stopNetworkMap.put("needPwd", "0");
				stopNetworkMap.put("changeReason", "reasontest");
				stopNetworkMap.put("authType", "AuthCheckB");
				stopNetworkMap.put("passWord", "");
				stopNetworkMap.put("certType", "IdCard");
				stopNetworkMap.put("certID", ""); 
				stopNetworkMap.put("oprRoam", "0");
				stopNetworkMap.put("IsRealSerSo", "0");
				stopNetworkMap.put("operatorID", "1101818");
				String stopNetworkStr = new JSONObject(stopNetworkMap)
						.toString();
				String result = HttpUtilDemo.stopNetwork(stopNetworkStr,
						stopUrl);
				String res_code = new JSONObject(result).getString("res_code");
				//4.这里记录日志,将停机号码都记录下来
				if ("0".equals(res_code)) {
					smsLog.setIsdowntime(1);
					smsLog.setCreateTime(new Date());
					smsLogService.updateById(smsLog);
				} else {
					System.out.println("停机接口调用失败**************");
				}
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 